<?php

Raise::load('core.RaiseObject');
Raise::load('core.RaiseApplication');
Raise::load('core.io.file.RaisePath');
Raise::load('core.reflection.RaiseVariable');

/**
 * RaiseAppPackageLoader class
 * loads application specific classes in the application directory
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package phpraise.core
 * @since 1.2
 */
class RaiseAppPackageLoader extends RaiseObject {

    /**
     * The RaiseApplication to load the package from
     * @var RaiseApplication
     */
    private $application;

    /**
     * Create a new RaiseApplication package loader
     * @param RaiseApplication $app The application to load
     */
    function __construct($app) {
        $this->application = $app;
    }

    /**
     * Load a package from the application
     * @param string $package package name
     */
    public function loadPackage($package) {
        $root = $this->application->rootPath();
        if ($root) {
            $path = RaisePath::combine($root, 'raise', $package, '*.php');
            $search = RaiseFileSystem::pathSearch($path);
            foreach ($search as $p) {
                self::loadClass($p);
            }
        }
    }

    /**
     * Load a specific class
     * @param string $path
     * @return boolean TRUE if success, FALSE otherwise.
     * @static
     */
    public static function loadClass($path) {
        $ok = include($path);
        if ($ok) {
            $machine = RaisePath::fileName($path);
            if (class_exists($machine) && in_array('IRaiseInitializable', class_implements($machine))) {
                call_user_func(array($machine, 'initialize'));
            }
        }
        return $ok;
    }

    /**
     * Load templates from the templates folder into RaiseTemplate
     * @todo is there a better way to load templates
     */
    public function loadTemplates() {
        $root = $this->application->rootPath();
        if ($root) {
            $search = RaiseFileSystem::pathSearch(RaisePath::combine($root, 'raise', 'template', '*.html'));
            foreach ($search as $i) {
                RaiseTemplate::loadTemplate(new RaiseFile($i));
            }
        }
    }

}